<template>
  <div class="article-list">
    <!-- 文章列表 -->
    <van-pull-refresh :success-text="refreshSuccessText" :success-duration="1500" v-model="refreshing"
      @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync='error'
        error-text='请求失败,请点击重试'>
        <article-item v-for="(item,ind) in list" :key="ind" :article="item" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 导入频道列表接口
import { getArticle } from '@/api/article.js'
import ArticleItem from '@/components/article-item'
export default {
  name: 'pageChannels',
  props: {
    channel: {
      type: Object,
      require: true
    }
  },
  data () {
    return {
      list: [], //  存储列表数据
      loading: false, // 控制数据加载
      finished: false, // 控制加载是否完成
      timestamp: null, // 请求下页的时间戳
      error: false, // 是否加载失败
      refreshing: false, // 上拉刷新
      refreshSuccessText: ''
    }
  },
  methods: {
    // 加载数据
    async onLoad () {
      try {
        const { data: res } = await getArticle({
          channel_id: this.channel.id, // 频道id
          timestamp: this.timestamp || Date.now(), //  时间戳
          with_top: 1 // 是否包含置顶   0 1包含
        })
        const { results } = res.data
        console.log(results)
        this.list.push(...results)

        // 设置加载状态
        this.loading = false

        // 判断是否已经加载完毕
        if (results.length) {
          // 获取下一页的时间戳
          this.timestamp = res.data.pre_timestamp
        } else {
          // 无数据可以获取  加载完成
          this.finished = true
        }
      } catch (err) {
        // console.log(err)
        // 加载失败  停止加载
        this.loading = false
        this.error = true
      }
    },
    // 清空数据
    async onRefresh () {
      try {
        const { data: res } = await getArticle({
          channel_id: this.channel.id, // 频道id
          timestamp: Date.now(), //  时间戳
          with_top: 1 // 是否包含置顶   0 1包含
        })
        const { results } = res.data
        // 刷新获取到的数据添加到顶部
        this.list.unshift(...results)

        // 关闭下拉刷新
        this.refreshing = false

        // 刷新提示文本
        this.refreshSuccessText = `刷新成功,更新了${results.length}数据`
      } catch (err) {
        // console.log(err)
        // 关闭下拉刷新
        this.refreshing = false
        this.$toast('刷新失败')
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {
    ArticleItem
  },
  created () { },
  mounted () { }
}
</script>

<style lang='less' scoped>
.article-list {
  height: 93vh;
  overflow-y: scroll;
}
</style>
